package mcia_gui;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;

/**
 * Main.java - starts the program and initializes variables.
 *
 * @author MCIA
 */
public class Main {

    public static int TIMER_FREQUENCY = 1;                                              //main timer freq. to ask from real CLs
    public static Timer mainTimer;                                                      //timer instance that asks db every defined period of time
    public static String dbName;                                                        //database name and connection
    public static DatabaseEss db;                                                       //makes connection to db
    public static JPanel currentPanel;                                                  //used to show first screen
    public static Container container;
    public static LogOn mainScreen;
    public static ArrayList<String[]> globalDefinitions = new ArrayList<String[]>();    //it is arraylist used for storing data connected with global scenes
    private static String queryFileDir = "sendQuery";                                   //directory of send query file that allows to set data into db
    public static boolean start = false;                                                //used to check if global scene sheduled was triggered

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException {
        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        //setting necessary database connections
        dbName = "mcia";
        db = new DatabaseEss(dbName);

        //starting Main Timer
        startTimer();

        //showing first screen - logOn screen
        mainScreen = new LogOn();
        currentPanel = new JPanel();
        container = mainScreen.getContentPane();
        container.add(currentPanel);
        mainScreen.setVisible(true);

        //setting position of window to middle of the screen
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension scrnsize = toolkit.getScreenSize();
        mainScreen.setLocation(scrnsize.width / 2 - (mainScreen.getWidth() / 2), scrnsize.height / 2 - (mainScreen.getHeight() / 2));
    }

    public static void startTimer() {
        //setting text to timerLabel
        mainTimer = new Timer();
        mainTimer.scheduleAtFixedRate(new TimerTask() {

            public void run() {

                updateDBstate();
                schedule();
            }
        }, 5000, TIMER_FREQUENCY * 1000);
    }

    public static void schedule() {
        //used to supervise if any global scene should be trrigered
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        System.out.println(dateFormat.format(date.getTime()));
        int a;
        if (!globalDefinitions.isEmpty()) {
            for (a = 0; a < globalDefinitions.size(); a++) {
                if (globalDefinitions.get(a)[1].equals(dateFormat.format(date.getTime())) && globalDefinitions.get(a)[2] != null && start == true) {
                    JOptionPane.showMessageDialog(currentPanel, "Started Global Scene: " + globalDefinitions.get(a)[0]);
                    System.out.println("STARTING SCENE: " + globalDefinitions.get(a)[0]);
                }
            }
        }
    }

    public static int updateDBstate() {
        //updating DB with information given in a file
        File descFile = new File(queryFileDir, "query.txt");
        if (descFile.exists()) {
            try {
                FileReader fr = new FileReader(descFile);
                BufferedReader br = new BufferedReader(fr);
                String line;
                int lineCount = 0;
                int howManyCommands = 0;
                String firstCLpart, secondCLpart;
                String clName;
                int delay = 0;

                //reading 0. line with number of commands
                if ((line = br.readLine()) != null) {
                    howManyCommands = Integer.parseInt(line);
                    lineCount++;
                } else {
                    System.out.println("Error with file: " + queryFileDir + "/query.txt). Wrong file structure. Line: " + lineCount);
                    return -3;
                }
                //reading 1. and 2. line (cl number)
                if ((line = br.readLine()) != null) {
                    firstCLpart = line;
                    lineCount++;
                } else {
                    System.out.println("Error with file: " + queryFileDir + "/query.txt). Wrong file structure. Line: " + lineCount);
                    return -3;
                }
                if ((line = br.readLine()) != null) {
                    secondCLpart = line;
                    lineCount++;
                } else {
                    System.out.println("Error with file: " + queryFileDir + "/query.txt). Wrong file structure. Line: " + lineCount);
                    return -3;
                }
                //making cl name
                clName = firstCLpart + "." + secondCLpart;
                System.out.println("CL name: " + clName);
                //reading 3. line (immediate change)
                if ((line = br.readLine()) != null) {
                    int value = Integer.parseInt(line);
                    if (value == 255) {
                        delay = 0;
                    } else {
                        //define how much delay depending on byte read
                    }
                    lineCount++;
                } else {
                    System.out.println("Error with file: " + queryFileDir + "/query.txt). Wrong file structure. Line: " + lineCount);
                    return -3;
                }

                for (int i = 0; i < howManyCommands; i++) {
                    int floorNumber = Integer.parseInt(firstCLpart);
                    int clNumber = Integer.parseInt(secondCLpart);
                    int lightNumber;
                    int lightBrightness;
                    int lightDelay;
                    //reading command lines
                    if ((line = br.readLine()) != null) {
                        lightNumber = Integer.parseInt(line);
                        lineCount++;
                    } else {
                        System.out.println("Error with file: " + queryFileDir + "/query.txt). Wrong file structure. Line: " + lineCount);
                        return -3;
                    }
                    if ((line = br.readLine()) != null) {
                        lightBrightness = Integer.parseInt(line);
                        lineCount++;
                    } else {
                        System.out.println("Error with file: " + queryFileDir + "/query.txt). Wrong file structure. Line: " + lineCount);
                        return -3;
                    }
                    if ((line = br.readLine()) != null) {
                        lightDelay = Integer.parseInt(line);
                        lineCount++;
                    } else {
                        System.out.println("Error with file: " + queryFileDir + "/query.txt). Wrong file structure. Line: " + lineCount);
                        return -3;
                    }
                    //we have all the values fot the light, we change the light in db
                    System.out.println("Light: " + lightNumber + " Brightness: " + lightBrightness);

                    db.stmt = db.conn.createStatement();
                    String query = "UPDATE units SET BRIGHTNESS = " + lightBrightness + " WHERE floor = " + floorNumber + " AND cl = " + clNumber + " AND light = " + lightNumber + "";
                    int results2 = db.stmt.executeUpdate(query);

                    if (results2 == 0) {
                        System.out.println("Error: Light " + lightNumber + " status not changed! Probably that light doesn't exist.");
                    }
                }

            } catch (Exception ex) {
                System.out.println("Error with file: " + ex + " Filename: query.txt");
                return -1;
            }
        } else {
            //file doesn't exits
            System.out.println("WARNING: File with db query not found (" + queryFileDir + "/query.txt).");
            return -2;
        }

        System.out.println("Database updated with real LIGHT states");

        return 0;
    }

    public static void changeFrame(JFrame c) {
        //used to switch frame
        container = c.getContentPane();
        mainScreen.setContentPane(container);
    }
}
